/*
 * @Description: 编辑更新日志弹窗组件
 * @Author: Rfan
 * @Date: 2022-06-11 9:24:01
 * @LastEditTime: 2022-06-11 15:08:59
 */

import { useEffect } from 'react';
import { Button, Form, Modal } from 'antd';
import type { FC } from 'react';
import ChangeLogFormItem from './common/ChangeLogFormItem';
import { formatDate } from '@/utils';
import { useChangeLogContext } from '../../contexts/ChangeLogContext';
import type { ICommonDialog } from '@/interfaces/global';

interface EditDialogProps extends ICommonDialog {
  data: any;
}

const EditDialog: FC<EditDialogProps> = (props) => {
  const { visible, data, onClose } = props;
  const { onEditChangeLog } = useChangeLogContext();
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      form.setFieldsValue(data);
    }
  }, [visible]);
  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增排序方法
  const onFinish = (values: any) => {
    values.updateTime = formatDate(values.updateTime, 'YYYY-MM-DD 00:00:00');
    onEditChangeLog({ ...data, ...values }).then(() => {
      onCancel();
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="编辑更新日志"
      visible={visible}
      width={650}
      onCancel={onCancel}
      footer={[
        <Button
          key="back"
          onClick={() => {
            onCancel();
          }}
        >
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={() => {
            submitFunc();
          }}
        >
          确定
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <ChangeLogFormItem />
      </Form>
    </Modal>
  );
};

export default EditDialog;
